package com.jfs.qy.config.component;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @Description 定时任务工具组件实现
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/11/4
 */
public class TaskExecutorReactorRealization implements TaskExecutorReactor {
    private static final Map<String, Future<?>> FUTURE_MAP = new ConcurrentHashMap<>();

    private final ScheduledExecutorService scheduledExecutorService;

    public TaskExecutorReactorRealization(ScheduledExecutorService scheduledExecutorService) {
        this.scheduledExecutorService = scheduledExecutorService;
    }

    @Override
    public Future<?> schedule(Task task, long initialDelay, long delay) {
     try {
         //防止任务已经启用
         stop(task.getKey());
         ScheduledFuture<?> scheduledFuture = this.scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, TimeUnit.MILLISECONDS);
         FUTURE_MAP.put(task.getKey(), scheduledFuture);
         return scheduledFuture;
     }catch (Exception e){
         e.printStackTrace();
     }
     return null;
    }

    @Override
    public Future<?> schedule(Runnable runnable, long initialDelay, long delay) {
        return this.scheduledExecutorService.scheduleWithFixedDelay(runnable, initialDelay, delay, TimeUnit.MILLISECONDS);
    }

    @Override
    public void stop(String key) {
        if (FUTURE_MAP.containsKey(key)) {
            Future<?> future = FUTURE_MAP.get(key);
            future.cancel(true);
            FUTURE_MAP.remove(key);
        }
    }

    @Override
    public boolean isRunning(String key) {
        if (FUTURE_MAP.containsKey(key)) {
            Future<?> future = FUTURE_MAP.get(key);
            if (future.isDone()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public ScheduledExecutorService getScheduledExecutorService() {
        return this.scheduledExecutorService;
    }
}
